package com.pz.cloud.framework.glory.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.pz.cloud.framework.base.dao.CommonDao;
import com.pz.cloud.framework.base.expection.CustomRuntimeException;
import com.pz.cloud.framework.base.service.BaseServiceImpl;
import com.pz.cloud.framework.business.glory.entity.Glory;
import com.pz.cloud.framework.business.glory.entity.GloryApply;
import com.pz.cloud.framework.business.glory.service.IGloryApplyService;
import com.pz.cloud.framework.business.glory.service.IGloryService;
import com.pz.cloud.framework.business.pzStudent.entity.PzStudentGpa;
import com.pz.cloud.framework.business.pzStudent.service.IPzStudentGpaService;
import com.pz.cloud.framework.business.pzStudent.service.IPzStudentPunishmentService;
import com.pz.cloud.framework.business.workflow.annotation.Workflow;
import com.pz.cloud.framework.glory.callback.GloryApplyCallback;
import com.pz.cloud.framework.glory.mapper.GloryApplyMapper;
import com.pz.cloud.framework.model.SqlBuilder;
import com.pz.cloud.framework.util.ExpressionHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
@Slf4j
public class GloryApplyServiceImpl extends BaseServiceImpl<GloryApplyMapper, GloryApply> implements IGloryApplyService {
    @Autowired
    private CommonDao commonDao;

    @Autowired
    private IGloryService gloryService;

    @Autowired
    private IPzStudentPunishmentService punishmentService;

    @Autowired
    private IPzStudentGpaService gpaService;

    @Workflow(callback = GloryApplyCallback.class)
    public boolean add(GloryApply entity) {
        checkRule(entity);
        boolean flag ;
        if(StringUtils.isEmpty(entity.getId())) {
            flag = super.save(entity);
        }else{
            flag = super.updateById(entity,true);
        }
        entity.getWorkflowModel().setHandlerId(entity.getInstructorId());
        return flag;
    }

    private void checkRule(GloryApply entity) {
        Assert.notEmpty(entity.getGlory(), "荣誉奖项为空");
        Glory glory = gloryService.findByCode(entity.getGlory());
        Assert.notNull(glory, "缺少配置，请联系管理员");
        String rule = glory.getRule();
        if (StringUtils.isBlank(rule)) {
            log.warn("荣誉奖项规则为空：{}", glory.getName());
            return;
        }

        Map<String, Object> map = new HashMap<>();
        Assert.notEmpty(entity.getStdNo(), "学号为空");
        Assert.notEmpty(entity.getPeriod(), "学年为空");
        Integer pnsCount = punishmentService.countByStdNo(entity.getStdNo());
        map.put("pnsCount", pnsCount);

        PzStudentGpa gpa = gpaService.findByStdNoAndPeriod(entity.getStdNo(), entity.getPeriod());
        PzStudentGpa lastGpa = gpaService.findByStdNoAndPeriod(entity.getStdNo(),
                Arrays.stream(entity.getPeriod().split("-")).mapToInt(Integer::parseInt)
                        .mapToObj(a -> String.valueOf(a - 1)).collect(Collectors.joining("-")));
        map.put("gpa", gpa);
        map.put("lastGpa", lastGpa);
        map.put("apply", entity);

        String parse = ExpressionHelper.parse(rule, map);
        if (!Boolean.parseBoolean(parse)) {
            throw new CustomRuntimeException(String.format("不符合申请[%s]的条件：%s", glory.getName(), glory.getRemark()));
        }
    }

    @Override
    public IPage<GloryApply> findPage(GloryApply entity) {
        SqlBuilder sqlBuilder = SqlBuilder.init(entity, null);
        sqlBuilder.filterDataScope(null,"user_id");
        IPage page = commonDao.findPage(sqlBuilder);
        return page;
    }
}
